#!/usr/bin/env python3
"""
Cleanup script to fix issues introduced by the previous LaTeX fixer script
"""

import os
import re
from pathlib import Path

def cleanup_file(filepath):
    """Clean up a single LaTeX file"""
    print(f"Cleaning up {filepath}")
    
    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            content = f.read()
        
        original_content = content
        
        # Fix the main issues introduced by the previous script
        
        # 1. Remove spurious \1 characters
        content = re.sub(r'\\1', '', content)
        
        # 2. Fix broken hyperref setup
        content = re.sub(r'    colorlinks=true,\n    linkcolor=blue,\n    filecolor=magenta,      \n    urlcolor=cyan,\n    citecolor=green,\}', 
                        'colorlinks=true,\n    linkcolor=blue,\n    filecolor=magenta,\n    urlcolor=cyan,\n    citecolor=green,', content)
        
        # 3. Fix broken algorithm captions
        content = re.sub(r'\\begin\{algorithm\}\[H\]\s*\\caption', r'\\begin{algorithm}[H]\n\\caption', content)
        
        # 4. Fix broken Chinese text in math mode (remove unnecessary \text{} wrappers around single characters)
        content = re.sub(r'\\text\{([一-龯])\}', r'\1', content)
        
        # 5. Fix spacing issues around Chinese text
        content = re.sub(r'\ \ \ \ \\', r'\\', content)
        
        # 6. Fix broken table placement
        content = re.sub(r'\\begin\{table\}\[H\]\\1\[H\]', r'\\begin{table}[H]', content)
        content = re.sub(r'\\begin\{figure\}\[H\]\\1\[htbp\]', r'\\begin{figure}[H]', content)
        content = re.sub(r'\\begin\{algorithm\}\[H\]\\1\[H\]', r'\\begin{algorithm}[H]', content)
        
        # 7. Fix algorithm commands that were broken
        content = re.sub(r'\\1\\caption', r'\\caption', content)
        
        # 8. Clean up extra spaces and formatting issues
        content = re.sub(r'\ \ \ \ \\EndIf', r'    \\EndIf', content)
        content = re.sub(r'\ \ \ \ \\EndFor', r'    \\EndFor', content)
        content = re.sub(r'\ \ \ \ \\State', r'        \\State', content)
        
        # 9. Fix broken markdown code blocks that should be LaTeX
        content = re.sub(r'```algorithm', r'\\begin{algorithm}[H]', content)
        content = re.sub(r'```', r'\\end{algorithm}', content)
        
        # Write the fixed content if changed
        if content != original_content:
            with open(filepath, 'w', encoding='utf-8') as f:
                f.write(content)
            print(f"  Cleaned up {filepath}")
            return True
        else:
            print(f"  No cleanup needed for {filepath}")
            return False
            
    except Exception as e:
        print(f"  Error cleaning up {filepath}: {e}")
        return False

def main():
    """Main cleanup function"""
    print("LaTeX Cleanup Script")
    print("=" * 30)
    
    # Get current directory
    base_dir = Path('.')
    
    # Find all .tex files
    tex_files = []
    
    # Main document
    main_doc = base_dir / 'cpp-function-call-tree-report.tex'
    if main_doc.exists():
        tex_files.append(main_doc)
    
    # Chapter files
    chapters_dir = base_dir / 'chapters'
    if chapters_dir.exists():
        tex_files.extend(chapters_dir.glob('*.tex'))
    
    if not tex_files:
        print("No .tex files found!")
        return
    
    print(f"Found {len(tex_files)} .tex files to clean up:")
    for f in tex_files:
        print(f"  {f}")
    
    print("\nCleaning up files...")
    print("-" * 20)
    
    processed_count = 0
    fixed_count = 0
    
    for tex_file in tex_files:
        processed_count += 1
        if cleanup_file(tex_file):
            fixed_count += 1
    
    print("-" * 20)
    print(f"Cleanup complete!")
    print(f"Files processed: {processed_count}")
    print(f"Files cleaned: {fixed_count}")

if __name__ == '__main__':
    main()